package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-wms/cache"
	"logi-wms/models"
	"strconv"
	"time"
)

func RoomAdd(c *gin.Context) {
	room_code := c.PostForm("room_code")
	room_name := c.PostForm("room_name")
	room_num := c.PostForm("room_num")

	data := models.Room{
		RoomCode: room_code,
		RoomName: room_name,
		RoomNum:  room_num,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_no := c.PostForm("order_no")
	mid, _ := strconv.Atoi(c.PostForm("mid"))

	data := models.Order{
		OrderNo: order_no,
		Mid:     mid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var orderlist []models.OrderList
	/*
			SELECT
		  orders.id as OrderId,
		  orders.order_no as OrderNo,
		  rooms.room_code as RoomCode,
		  rooms.room_name as RoomName,
		  rooms.room_num as RoomNum
		FROM
		  rooms
		  LEFT JOIN orders ON rooms.id = orders.mid
	*/
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("rooms").
			Select(
				"orders.id as OrderId",
				"orders.order_no as OrderNo",
				"rooms.room_code as RoomCode",
				"rooms.room_name as RoomName",
				"rooms.room_num as RoomNum",
			).
			Joins("LEFT JOIN orders ON rooms.id = orders.mid").
			Offset(offset).Limit(size).Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": orderlist,
	})
	return
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var orderlist []models.OrderList
	/*
			SELECT
		  orders.id as OrderId,
		  orders.order_no as OrderNo,
		  rooms.room_code as RoomCode,
		  rooms.room_name as RoomName,
		  rooms.room_num as RoomNum
		FROM
		  rooms
		  LEFT JOIN orders ON rooms.id = orders.mid
	*/
	redis_key := "list_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("rooms").
			Select(
				"orders.id as OrderId",
				"orders.order_no as OrderNo",
				"rooms.room_code as RoomCode",
				"rooms.room_name as RoomName",
				"rooms.room_num as RoomNum",
			).
			Joins("LEFT JOIN orders ON rooms.id = orders.mid").
			Where("orders.mid=?", id).Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": orderlist,
	})
	return
}
